package com.tevintao.marketingsystem.services;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Process;
import android.os.RemoteException;
import android.text.TextUtils;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tevintao.marketingsystem.activity.ActSetDevice;
import com.tevintao.marketingsystem.activity.ActSetting;
import com.tevintao.marketingsystem.activity.MainActivity;
import com.tevintao.marketingsystem.aidl.ICallback;
import com.tevintao.marketingsystem.aidl.ITaskCallback;
import com.tevintao.marketingsystem.aidl.ITaskLogic;
import com.tevintao.marketingsystem.commen.JsonUtils;
import com.tevintao.marketingsystem.commen.TaskBean;
import com.tevintao.marketingsystem.commen.UrlConfig;
import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.provider.ContactsManager;
import com.tevintao.marketingsystem.provider.ChatNewChatDB;
import com.tevintao.marketingsystem.task.ReportIcon;
import com.tevintao.marketingsystem.task.ReportMessage;
import com.tevintao.marketingsystem.task.WxTaskProcess;
import com.tevintao.marketingsystem.task.WxUiViewConfig;
import com.tevintao.marketingsystem.tool.DownloadFile;
import com.tevintao.marketingsystem.tool.NetWorkTool;
import com.tevintao.marketingsystem.tool.PackageTool;
import com.tevintao.marketingsystem.tool.PhoneTool;
import com.tevintao.marketingsystem.tool.ShellOperationTool;
import com.tevintao.marketingsystem.tool.SystemPathTool;
import com.tevintao.marketingsystem.xposted.HookAudioRecord;
import com.tevintao.marketingsystem.xposted.WxTaskManger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

/**
 * 修改代码 注意是否会小功能
 * 1，设置任务的时候等待微信启动 countDownStartTask
 * 2，定时检查进程是否存活 checkTaskAlive
 */
public class TaskLogicService extends BaseHandlerServices {

    public static final String ACTION_START_TASK_LOGIC_SERVICE = "com.tevintao.marketingsystem.services.TaskLogicService";
    public static final String ACTION_TEST_TASK = "ACTION_TEST_TASK";

    public static final String TASK_TAG_SUCCESS = "TASK_TAG_SUCCESS";
    private long mWaitingProcessTime = 0;
    private static final int MAX_WAIT_PROCESS_TIME = 30 * 1000;//最大等待启动时间，10秒

    public static final String TAG_CHECK_TASK_ALIVE = "TAG_CHECK_TASK_ALIVE";
    public static final String TAG_GET_CURRENT_DEVICE_INFO = "TAG_GET_CURRENT_DEVICE_INFO";
    public static final String KEY_GET_CURRENT_DEVICE_INFO = "key_REQUEST_MESSAGE_STEPget_current_device_info";

    public static final String TAG_GET_CURRENT_LOCATION_INFO = "TAG_GET_CURRENT_LOCATION_INFO";
    public static final String KEY_GET_CURRENT_LOCATION_INFO = "key_get_current_location_info";

    private static final int REQUEST_MESSAGE_STEP = 10 * 1000;
    private static final int SELF_CHECK_TASK_ALIVE = 5 * 60 * 1000;

    public static boolean mTaskRunning = true;
    /**
     * 获取任务的时候就是true，用于标识正在设置任务
     */
    private volatile boolean mGetTaskTime = false;
    private long mLastSetTaskTime = 0;
    /**
     * 开始任务之后需要等待进程启动后才开始设置任务，所以检测不到微信运行中
     */
    private volatile boolean mWaitProcess = false;

    private long mCanRequestTime = 0; //任务执行完毕在等待的时候，

    private RequestQueue queue = null;

    private static Random mRandom = new Random();

    public TaskLogicService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter mTestIntentFilter = new IntentFilter(ACTION_TEST_TASK);
        registerReceiver(mTestReceiver, mTestIntentFilter);
        queue = Volley.newRequestQueue(this);

        if (MockServices.checkClient()) {
            try {
                MockServices.getClient().registerSyncCallback(TAG_CHECK_TASK_ALIVE, checkTaskAlive, Process.myUid(), Process.myPid());
            } catch (RemoteException e) {
                e.printStackTrace();
                LogManager.getInstance().logError(TAG_CHECK_TASK_ALIVE + " register RemoteException " + e.getMessage());
            }

            try {
                MockServices.getClient().registerSyncCallback(TAG_GET_CURRENT_DEVICE_INFO, getDeviceInfo, Process.myUid(), Process.myPid());
            } catch (RemoteException e) {
                e.printStackTrace();
                LogManager.getInstance().logError(TAG_GET_CURRENT_DEVICE_INFO + " register RemoteException " + e.getMessage());
            }

            try {
                MockServices.getClient().registerSyncCallback(TAG_GET_CURRENT_LOCATION_INFO, getLocationInfo, Process.myUid(), Process.myPid());
            } catch (RemoteException e) {
                e.printStackTrace();
                LogManager.getInstance().logError(TAG_GET_CURRENT_LOCATION_INFO + " register RemoteException " + e.getMessage());
            }
        }

        registerReceiver(mKeyReceiver, new IntentFilter(ACTION_KEY_RECEIVER));
        registerReceiver(mReportReceiver, new IntentFilter(ACTION_KEY_REPORT_CHAT));
        registerReceiver(mRebootReceiver, new IntentFilter(ACTION_REBOOT));
        registerReceiver(mSystemErrorReceiver, new IntentFilter(ACTION_REPORT_SYSTEM_ERROR));
        IntentFilter intentFilter = new IntentFilter(ACTION_KEY_REPORT_ACCOUNT_ICON);
        intentFilter.addAction(ACTION_KEY_REPORT_FRIEND_ICON);
        intentFilter.addAction(ACTION_KEY_REPORT_FRIEND_SEX);

        registerReceiver(mReportIconPath, intentFilter);


        mHandler.postDelayed(mCheckNewMessage, REQUEST_MESSAGE_STEP);
//        mHandler.postDelayed(mSelfCheckTaskAliveRunnable, SELF_CHECK_TASK_ALIVE);

        if (MockServices.checkClient()) {
            try {
                MockServices.getClient().startCheckTask();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public IBinder onBind(Intent intent) {
        return taskLogicBinder;
    }

    private Map<String, ITaskCallback> mCallbacksMap = new HashMap<>();

    private String mDeviceName = "";
    private String mAccount = "";
    private String mDeviceString = "";
    private String mGpsString = "";
    private int mTaskId = 0;

    /**
     * 记录正在运行的taskbean，避免有些进程没有启动，启动任务成功后，进程再次启动，没有给进程设置任务
     */
    private TaskBean mTaskBean = null;

    /**
     * 请求服务器错误叠加次数
     */
    private int mNetErrorTimes = 0;



    private BroadcastReceiver mTestReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, Intent intent) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    PackageTool.stopApp(AccountManager.WX_PACKAGE_NAME);
                    if (PackageTool.aliveMore5(TaskLogicService.this, AccountManager.WX_PACKAGE_NAME)) {
                        LogManager.getInstance().logError("微信没有杀死");
                    }

                    JSONObject jo = new JSONObject();
                    try {
                        jo.put(WxUiViewConfig.KEY_USER_NAME, "9509445569519");
                        jo.put(WxUiViewConfig.KEY_PASSWORD, "txy16899052txy");
                        jo.put(WxUiViewConfig.KEY_SEARCH_FRIEND_KEY_WORDS, "18612450138");
                        jo.put(WxUiViewConfig.KEY_NEED_CHAT_NICK_NAME, "1938");
                        jo.put(WxUiViewConfig.KEY_CHAT_CONTENT, "你好，我是第一条");
                        jo.put(WxUiViewConfig.KEY_MY_SIGNATURE, "清晨");
                        jo.put(HookAudioRecord.KEY_AUDIO_PATH, MainActivity.silkPathPcm);
//                        jo.put(WxUiViewConfig.CHANGE_ICON_PATH, "/mnt/sdcard/ms/pic/mmexport1480400055383_nH0vbQC.jpg");
//                        JSONArray jsonArray = new JSONArray();
//                        jsonArray.put("/mnt/sdcard/ms/pic/mmexport1480400055383_nH0vbQC.jpg");
//                        jsonArray.put("/mnt/sdcard/ms/pic/mmexport1480400063261_WlbDMDQ.jpg");
//                        jo.put(WxUiViewConfig.KEY_FRIEND_CIRCLE_PATHS, jsonArray.toString());
//                        String testJs = "javascript:alink =document.getElementsByTagName('a')[0] ; var ev = document.createEvent('HTMLEvents');  ev.initEvent('click', false, true); alink.dispatchEvent(ev);  ";
//                        String testJs = "javascript:alink =document.getElementsByTagName('a')[0] ;  alink.click(); ";
//                        String testJs = "javascript:alink =document.getElementsByTagName('a')[0] ;  alink.click();  ";
//                        String testJs = "javascript:alink = document.getElementsByTagName('li')[0] ; var liRect = alink.getBoundingClientRect();  window.local_obj.setRect(liRect.top + ',' + liRect.left + ',' + liRect.right + ',' + liRect.bottom + ',' + liRect.width + ',' + liRect.height);  ";
//                        String testJs = "javascript:alink = document.getElementsByTagName('li')[0] ; var liRect = alink.getBoundingClientRect();  window.local_obj.showLink('alink.outerHTML = ' + liRect + ' liRect.top = ' + liRect.top + ' liRect.left = ' + liRect.left + ' liRect.right = ' + liRect.right + ' liRect.bottom = ' + liRect.bottom + ' liRect.width = ' + liRect.width + ' liRect.height = ' + liRect.height);  ";
//                        jo.put(WxUiViewConfig.KEY_FORWARD_SUBSCRIBE_JAVA_SCRIBE, testJs);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (MockServices.checkClient()) {
                        try {
                            MockServices.getClient().clearLocation();
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                    TaskBean bean = new TaskBean();
                    bean.setTaskId(WxTaskProcess.TASK_ID_WAIT);
                    bean.setMaxTime(5);
                    bean.setExtra(jo.toString());
                    bean.setBack2MainLauncher(false);
                    mTaskId = bean.getTaskId();

                    LogManager.getInstance().logInfo("mTaskId = " + mTaskId);
                    syncDeviceInfo();
                    readLocalDeviceInfo();
                    readLocationInfo();

                    countDownStartTask(bean);
                    PackageTool.launchAppFormPackage(context, AccountManager.WX_PACKAGE_NAME);
                }
            });
        }
    };

    /**
     * device = ''
     * account = ''
     * task_id = 0
     * state = 0
     * msg = ''
     * business = 0
     * have_location = 0
     * netType = -1
     *
     * @param state 状态
     * @param msg   信息
     */

    public void getTask(final int state, final String msg) {
//        if (!canRequest()) {
//            LogManager.getInstance().logError("canRequest return false");
//            //已经有任务执行了，就不在请求任务
//            return;
//        }
        if (!mTaskRunning) {
            LogManager.getInstance().logInfo("当前任务暂停 taskRequest");
            return;
        }
        if (TextUtils.isEmpty(mDeviceName) || TextUtils.isEmpty(mAccount)) {
            if (!syncDeviceInfo()) {
                return;
            }
        }

        if (NetWorkTool.getAirplaneMode(this)) {
            setAirPlan(false);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getTask(state, msg);
                }
            }, 20000);
            return;
        }

        boolean haveLocation = AccountManager.haveLocation();
        LogManager.getInstance().logInfo("haveLocation = " + haveLocation);
        int locationInt = haveLocation ? 1 : 0;
        boolean business = ActSetting.isBusinessVersion(this);
        LogManager.getInstance().logInfo("business = " + business);
        int businessInt = business ? 1 : 0;
        int netType = PhoneTool.getMobileTypeInt(this);
        String msgCode = "";
        try {
            msgCode = URLEncoder.encode(msg, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = String.format(UrlConfig.URL_GET_TASK, mDeviceName, mAccount, mTaskId, state, msgCode, businessInt, locationInt, netType);
        LogManager.getInstance().logInfo("getTask url = " + url);

        JsonObjectRequest mReportJson = new JsonObjectRequest(url, new JSONObject(), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(final JSONObject jsonObject) {
                LogManager.getInstance().logInfo(jsonObject.toString());
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mNetErrorTimes = 0;
                        onGetTaskSuccess(jsonObject.toString());
                        mGetTaskTime = false;
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (null != error && error.getMessage() != null) {
                    LogManager.getInstance().logError("getTask error msg =  " + error.getMessage());
                } else {
                    LogManager.getInstance().logError("getTask error msg = null ");
                }
                mNetErrorTimes++;
                LogManager.getInstance().logInfo("mNetErrorTimes " + mNetErrorTimes);
                if (mNetErrorTimes > 5) {
                    mNetErrorTimes = 0;
                    if (WxTaskProcess.DEBUG_MODEL)
                        ShellOperationTool.reBoot();
                    return;
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getTask(state, msg);
                    }
                }, 3000);
//                mGetTaskTime = false;
            }
        });
        mGetTaskTime = true;
        queue.add(mReportJson);
    }

    private boolean canRequest() {
        if (!mTaskRunning) {
            return false;
        }
        if (mGetTaskTime) {
            return false;
        } else if (mWaitProcess) {
            return false;
        } else if (taskRun()) {
            return false;
        } else if (System.currentTimeMillis() < mCanRequestTime) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 本地处理错误，上报到服务器，便于服务器处理
     *
     * @param state   状态
     * @param message 提示信息
     */
    private void localLogicError(final int state, final String message) {
        LogManager.getInstance().logInfo("localLogicError " + state + " " + message);
        MainActivity.messageChange(this, "帐号:" + mAccount + " 状态:" + state + " " + message);
//        LogManager.getInstance().logInfo("localLogicError = " + lastLogicError);
//        if (lastLogicError < 10 * 60 * 1000) {
//            lastLogicError += 60 * 1000;
//        }
//        mHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                getTask(state, message);
//            }
//        }, lastLogicError);
    }

    private String onGetTaskSuccess(String json) {
        TaskBean taskBean = JsonUtils.fromJson(json, TaskBean.class);
        if (TextUtils.isEmpty(taskBean != null ? taskBean.getAccount() : null)) {
            localLogicError(WxTaskManger.TASK_SATE_LOCAL_LOGIC_ERROR, "下发任务失败，帐号为空!");
            return "下发任务失败，帐号为空!";
        }
        boolean processTask = preProcessTask(taskBean);
        if (!processTask) {
            localLogicError(WxTaskManger.TASK_SATE_PROCESS_TASK, "预处理task错误，目前只有下载图片");
        }
        if (mAccount.equals(taskBean.getAccount())) {
            //帐号相同也有可能需要换位置信息，所以写上
            mTaskId = taskBean.getTaskId();
            LogManager.getInstance().logInfo("" + taskBean.getExtra());
            try {
                MockServices.getClient().clearLocation();//清理掉位置信息
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            syncDeviceInfo();
            readLocalDeviceInfo();

            taskBean.setBack2MainLauncher(true);
            boolean startWx = PackageTool.launchAppFormPackage(this, AccountManager.WX_PACKAGE_NAME);
            LogManager.getInstance().logInfo("启动微信 ：" + startWx);
            //同一个帐号，只需要开始执行任务即可
            if (!TextUtils.isEmpty(taskBean.getLocation())) {
                boolean writeLocation = AccountManager.writeLocation(taskBean.getLocation());
                LogManager.getInstance().logInfo("写入位置信息 " + writeLocation);
            }
            readLocationInfo();
            countDownStartTask(taskBean);
        } else {
            clearInfo();
            try {
                MockServices.getClient().clearLocation();//清理掉位置信息
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            //不是同一个帐号需要切换帐号，和切换各类信息等
            setAirPlan(true);
            PackageTool.stopApp(AccountManager.WX_PACKAGE_NAME);
            if (PackageTool.aliveMore5(this, AccountManager.WX_PACKAGE_NAME)) {
                LogManager.getInstance().logError("微信没有杀死");
                localLogicError(WxTaskManger.TASK_SATE_LOCAL_LOGIC_ERROR, "微信没有杀死");
                return "微信没有杀死";
            }
            String switchSuccess = AccountManager.getInstance(this).switchContext(taskBean.getAccount());
            if (AccountManager.SUCCESS_TAG.equals(switchSuccess)) {
                LogManager.getInstance().logInfo("切换帐号成功 " + taskBean.getAccount());
                if (!TextUtils.isEmpty(taskBean.getLocation())) {
                    boolean writeLocation = AccountManager.writeLocation(taskBean.getLocation());
                    LogManager.getInstance().logInfo("写入位置信息 " + writeLocation);
                }
            } else {
                LogManager.getInstance().logError("切换帐号失败 " + switchSuccess);
                localLogicError(WxTaskManger.TASK_SATE_LOCAL_LOGIC_ERROR, "切换帐号失败");
                return "切换帐号失败";
            }
//            if (!changeContacts) {
//                LogManager.getInstance().logError("切换通讯录失败");
//            }
            setAirPlan(false);
            mAccount = taskBean.getAccount();

            if (!readLocalDeviceInfo()) {
                LogManager.getInstance().logError("onGetTaskSuccess 读取设备信息失败");
                localLogicError(WxTaskManger.TASK_SATE_LOCAL_LOGIC_ERROR, "onGetTaskSuccess 读取设备信息失败");
                return "读取设备信息失败";
            }
            if (!readLocationInfo()) {
                LogManager.getInstance().logError("读取位置失败");
                localLogicError(WxTaskManger.TASK_SATE_LOCAL_LOGIC_ERROR, "读取位置失败");
                return "读取位置失败";
            }

            mTaskId = taskBean.getTaskId();
            boolean startWx = PackageTool.launchAppFormPackage(this, AccountManager.WX_PACKAGE_NAME);
            if (!startWx) {
                LogManager.getInstance().logError("启动微信失败");
                localLogicError(WxTaskManger.TASK_SATE_LOCAL_LOGIC_ERROR, "启动微信失败");
                return "启动微信失败";
            }
            taskBean.setBack2MainLauncher(false);
            countDownStartTask(taskBean);
        }
        return TASK_TAG_SUCCESS;
    }


    /**
     * 启动微信倒计时
     *
     * @param taskBean 启动任务数据Bean
     */
    private void countDownStartTask(TaskBean taskBean) {
        mWaitProcess = true;
        mWaitingProcessTime = System.currentTimeMillis();
        waitWxProcessStartAndStartTask(taskBean);
    }

    private void waitWxProcessStartAndStartTask(final TaskBean taskBean) {
        if (System.currentTimeMillis() - mWaitingProcessTime > MAX_WAIT_PROCESS_TIME) {
            LogManager.getInstance().logError("等待微信启动时间超过20秒");
            localLogicError(WxTaskManger.TASK_SATE_LOCAL_LOGIC_ERROR, "等待微信启动时间超过20秒");
            mWaitProcess = false;
            return;
        }
        ITaskCallback callback = mCallbacksMap.get(AccountManager.WX_PACKAGE_NAME);
        try {
            if (null != callback && callback.clientAlive()) {
                startTask(taskBean);
                mWaitProcess = false;
                return;
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                waitWxProcessStartAndStartTask(taskBean);
            }
        }, 1000);
    }


    private String startTask(TaskBean taskBean) {
        mTaskBean = taskBean;
        LogManager.getInstance().logInfo("startTask");
        Set<Map.Entry<String, ITaskCallback>> entries = mCallbacksMap.entrySet();
        LogManager.getInstance().logInfo("startTask mCallbacksMap size = " + mCallbacksMap.size());
        for (Map.Entry<String, ITaskCallback> entry : entries) {
            String key = entry.getKey();
            ITaskCallback callback = entry.getValue();
            Bundle bundle = new Bundle();
            bundle.putInt(WxTaskManger.KEY_TASK_ID, taskBean.getTaskId());
            bundle.putInt(WxTaskManger.KEY_TASK_MAX_TIME, taskBean.getMaxTime());
            bundle.putString(WxTaskManger.KEY_TASK_EXTRA, taskBean.getExtra());
            bundle.putBoolean(WxTaskManger.KEY_NEED_BACK_2_MAIN, taskBean.isBack2MainLauncher());
            try {
                boolean setTaskSuccess = callback.startTask(bundle);
                LogManager.getInstance().logInfo("设置任务 " + (setTaskSuccess ? "成功" : "失败") + " process = " + key + " callback.processRun() = " + callback.processRun());
            } catch (RemoteException e) {
                e.printStackTrace();
                LogManager.getInstance().logError("checkCallable RemoteException " + e.toString());
            }
        }
        return TASK_TAG_SUCCESS;
    }


    private final ITaskLogic.Stub taskLogicBinder = new ITaskLogic.Stub() {
        @Override
        public boolean registerSyncCallback(String key, ITaskCallback callBack) throws RemoteException {
            LogManager.getInstance().logInfo("TaskLogicService registerSyncCallback  key = " + key + " callBack = " + callBack);
            if (TextUtils.isEmpty(key)) {
                LogManager.getInstance().logError("fromProcessName is null");
            } else {
                mCallbacksMap.put(key, callBack);
                mHandler.postDelayed(mNewProcessStartTask, 100);
            }
            return true;
        }

        @Override
        public boolean taskFinish(final int state, final String extra) throws RemoteException {
            LogManager.getInstance().logInfo("taskFinish state = " + state + " extra = " + extra);
            int delayTime;
            boolean business = ActSetting.isBusinessVersion(TaskLogicService.this);
            if (business) {
                delayTime = 1;
                if (mTaskId == WxTaskProcess.TASK_ID_ADD_NEARBY_FRIEND) {
                    LogManager.getInstance().logInfo("定位完毕删除定位信息");
                    AccountManager.getInstance(TaskLogicService.this).removeLocation();
                }
            } else {
                delayTime = (mRandom.nextInt(10) + 10) * 1000;
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        sendKeyEvent(TaskLogicService.this, INPUT_TYPE_HOME);
                    }
                }, 3000);
            }

            mCanRequestTime = System.currentTimeMillis() + delayTime;
            mHandler.postDelayed(mStopAllProcessTask, 100);
            mTaskBean = null;
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getTask(state, extra);
                }
            }, delayTime);

            return true;
        }

        @Override
        public boolean serviceIsAlive() throws RemoteException {
            return true;
        }
    };

    private Runnable mNewProcessStartTask = new Runnable() {
        @Override
        public void run() {
            LogManager.getInstance().logInfo("有新的进程，启动任务");
            Set<Map.Entry<String, ITaskCallback>> entries = mCallbacksMap.entrySet();
            for (Map.Entry<String, ITaskCallback> entry : entries) {
                String key = entry.getKey();
                ITaskCallback callback = entry.getValue();
                try {
                    boolean run = callback.processRun();
                    if (!run && null != mTaskBean) {
                        Bundle bundle = new Bundle();
                        bundle.putInt(WxTaskManger.KEY_TASK_ID, mTaskBean.getTaskId());
                        bundle.putInt(WxTaskManger.KEY_TASK_MAX_TIME, mTaskBean.getMaxTime());
                        bundle.putString(WxTaskManger.KEY_TASK_EXTRA, mTaskBean.getExtra());

                        boolean setTaskSuccess = callback.startTask(bundle);
                        LogManager.getInstance().logInfo(key + "  mNewProcessStartTask 设置任务 " + (setTaskSuccess ? "成功" : "失败"));
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                    LogManager.getInstance().logError("mNewProcessStartTask RemoteException " + e.toString());
                }
            }
        }
    };

    private Runnable mStopAllProcessTask = new Runnable() {
        @Override
        public void run() {
            Set<Map.Entry<String, ITaskCallback>> entries = mCallbacksMap.entrySet();
            for (Map.Entry<String, ITaskCallback> entry : entries) {
                String key = entry.getKey();
                ITaskCallback callback = entry.getValue();
                try {
                    boolean stop = callback.stopTask();
                    LogManager.getInstance().logInfo("key = " + key + " STOP TASK = " + stop);
                } catch (RemoteException e) {
                    e.printStackTrace();
                    LogManager.getInstance().logError("checkCallable RemoteException " + e.toString());
                }
            }
        }
    };


    private boolean syncDeviceInfo() {
        mDeviceName = SystemPathTool.getOutPutContent(ActSetDevice.device_name_file);
        String newDataPath = AccountManager.MM_DATA_ROOT + "/" + AccountManager.ACCOUNT_NAME_FILE_NAME;
        mAccount = SystemPathTool.getOutPutContent(newDataPath);
        LogManager.getInstance().logError("syncDeviceInfo mCurrentDeviceName = " + mDeviceName + " mAccount = " + mAccount);
        Intent intent = new Intent(MainActivity.ACTION_UPDATE_ACCOUNT);
        Bundle bundle = new Bundle();
        bundle.putString(MainActivity.KEY_UPDATE_ACCOUNT, mAccount);
        intent.putExtras(bundle);
        sendBroadcast(intent);
        return !TextUtils.isEmpty(mDeviceName);
    }

    /**
     * 读取当前帐号的设备信息
     *
     * @return 读取是否成功
     */
    private boolean readLocalDeviceInfo() {
        if (SystemPathTool.exitFile(AccountManager.DEVICE_FILE)) {
            String json = SystemPathTool.getOutPutContent(AccountManager.DEVICE_FILE);
            if (TextUtils.isEmpty(json)) {
                LogManager.getInstance().logError("readLocalDeviceInfo updateDeviceJsonFromLocal json is null");
                return false;
            }
            String decode = null;
            try {
                decode = URLDecoder.decode(json, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (TextUtils.isEmpty(decode)) {
                return false;
            } else {
                mDeviceString = decode;
                LogManager.getInstance().logInfo("当前设备信息 = " + mDeviceString);
                return true;
            }
        } else {
            if (AccountManager.writeDeviceInfo().equals(AccountManager.SUCCESS_TAG)) {
                LogManager.getInstance().logError("补充设备信息成功");
                if (SystemPathTool.exitFile(AccountManager.DEVICE_FILE)) {
                    String json = SystemPathTool.getOutPutContent(AccountManager.DEVICE_FILE);
                    if (TextUtils.isEmpty(json)) {
                        LogManager.getInstance().logError("readLocalDeviceInfo updateDeviceJsonFromLocal json is null");
                        return false;
                    }
                    String decode = null;
                    try {
                        decode = URLDecoder.decode(json, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    if (TextUtils.isEmpty(decode)) {
                        return false;
                    } else {
                        mDeviceString = decode;
                        LogManager.getInstance().logInfo("当前设备信息 = " + mDeviceString);
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 读取当前帐号的位置信息
     *
     * @return 读取是否成功
     */
    private boolean readLocationInfo() {
        if (SystemPathTool.exitFile(AccountManager.LOCATION_FILE)) {
            String json = SystemPathTool.getOutPutContent(AccountManager.LOCATION_FILE);
            if (TextUtils.isEmpty(json)) {
                LogManager.getInstance().logError("updateDeviceJsonFromLocal json is null");
                return false;
            }
            String decode = null;
            try {
                decode = URLDecoder.decode(json, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (TextUtils.isEmpty(decode)) {
                return false;
            } else {
                mGpsString = decode;
                LogManager.getInstance().logInfo("当前位置信息 = " + mGpsString);
                return true;
            }
        }
        return false;
    }

    private boolean taskRun() {
        if (PackageTool.aliveMore5(this, AccountManager.WX_PACKAGE_NAME)) {
            LogManager.getInstance().logError("微信还活者");
            ITaskCallback callback = mCallbacksMap.get(AccountManager.WX_PACKAGE_NAME);
            try {
                if (null != callback && callback.processRun()) {
                    return true;
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        return false;
    }


    /**
     * 1，获取任务过程中
     * 2，设置任务过程中
     * 3，运行过程中
     */
    private ICallback checkTaskAlive = new ICallback.Stub() {
        @Override
        public Bundle callBack(Bundle bundle) throws RemoteException {
            if (!mTaskRunning) {
                LogManager.getInstance().logInfo("当前任务暂停 checkTaskAlive");
                return new Bundle();
            }
            if (mGetTaskTime) {
                mLastSetTaskTime++;
                if (mLastSetTaskTime > 5) {
                    mLastSetTaskTime = 0;
                    TaskLogicService.this.sendBroadcast(new Intent(ACTION_REBOOT));
                    LogManager.getInstance().logInfo("TaskLogicService is set task many times ");
                } else {
                    LogManager.getInstance().logInfo("TaskLogicService is set task");
                }
                return new Bundle();
            } else if (mWaitProcess) {
                LogManager.getInstance().logInfo("TaskLogicService is waiting process");
                return new Bundle();
            } else if (taskRun()) {
                LogManager.getInstance().logInfo("TaskLogicService weixin is running");
                return new Bundle();
            } else if (System.currentTimeMillis() < mCanRequestTime) {
                LogManager.getInstance().logInfo("任务执行完毕，正在等待");
                return new Bundle();
            } else {
                LogManager.getInstance().logError("当前服务没有运行");
                mHandler.postDelayed(mResetTask, 5000);
                return new Bundle();
            }
        }
    };

    private Runnable mSelfCheckTaskAliveRunnable = new Runnable() {
        @Override
        public void run() {
            LogManager.getInstance().logInfo("mSelfCheckTaskAliveRunnable selfCheckTaskAlive");
            mHandler.removeCallbacks(mSelfCheckTaskAliveRunnable);
            selfCheckTaskAlive();
            mHandler.postDelayed(mSelfCheckTaskAliveRunnable, 5 * 60 * 1000);
        }
    };

    private void selfCheckTaskAlive() {
        LogManager.getInstance().logInfo("selfCheckTaskAlive");
        if (!mTaskRunning) {
            LogManager.getInstance().logInfo("selfCheckTaskAlive 当前任务暂停 checkTaskAlive");
        }
        if (mGetTaskTime) {
            mLastSetTaskTime++;
            if (mLastSetTaskTime > 5) {
                mLastSetTaskTime = 0;
                mHandler.postDelayed(mResetTask, 5000);
                LogManager.getInstance().logInfo("selfCheckTaskAlive TaskLogicService is set task many times ");
                TaskLogicService.this.sendBroadcast(new Intent(ACTION_REBOOT));
            } else {
                LogManager.getInstance().logInfo("selfCheckTaskAlive TaskLogicService is set task");
            }
        } else if (mWaitProcess) {
            LogManager.getInstance().logInfo("selfCheckTaskAlive TaskLogicService is waiting process");
        } else if (taskRun()) {
            LogManager.getInstance().logInfo("selfCheckTaskAlive TaskLogicService weixin is running");
        } else if (System.currentTimeMillis() < mCanRequestTime) {
            LogManager.getInstance().logInfo("selfCheckTaskAlive 任务执行完毕，正在等待");
        } else {
            LogManager.getInstance().logError("selfCheckTaskAlive 当前服务没有运行");
            mHandler.postDelayed(mResetTask, 5000);
        }
    }

    private Runnable mResetTask = new Runnable() {
        @Override
        public void run() {
            PackageTool.stopApp(AccountManager.WX_PACKAGE_NAME);
            clearInfo();
            getTask(0, "当前服务没有运行");
        }
    };

    private void clearInfo() {
        mAccount = "";
        mDeviceString = "";
        mTaskId = 0;
        mTaskBean = null;
    }

    private ICallback getDeviceInfo = new ICallback.Stub() {
        @Override
        public Bundle callBack(Bundle bundle) throws RemoteException {
            Bundle resultBundle = new Bundle();
            resultBundle.putString(KEY_GET_CURRENT_DEVICE_INFO, mDeviceString);
            return resultBundle;
        }
    };

    private ICallback getLocationInfo = new ICallback.Stub() {
        @Override
        public Bundle callBack(Bundle bundle) throws RemoteException {
            Bundle resultBundle = new Bundle();
            resultBundle.putString(KEY_GET_CURRENT_LOCATION_INFO, mGpsString);
            return resultBundle;
        }
    };

    public static String ACTION_KEY_RECEIVER = "ACTION_KEY_RECEIVER";
    public static final String KEY_INPUT_KEY = "KEY_INPUT_KEY";

    public static final int INPUT_TYPE_BACK = 1;
    public static final int INPUT_TYPE_ENTER = 2;
    public static final int INPUT_TYPE_HOME = 3;

    private BroadcastReceiver mKeyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            if (null != bundle) {
                int inputType = bundle.getInt(KEY_INPUT_KEY);
                if (inputType == INPUT_TYPE_BACK) {
                    ShellOperationTool.goBack();
                } else if (inputType == INPUT_TYPE_ENTER) {
                    ShellOperationTool.inputKeyEvent();
                } else if (inputType == INPUT_TYPE_HOME) {
                    ShellOperationTool.goAndroidHome();
                }
            }
        }
    };

    public static final String ACTION_KEY_REPORT_CHAT = "ACTION_KEY_REPORT_CHAT";

    public static final String KEY_REPORT_CHAT_TALKER = "KEY_REPORT_CHAT_TALKER";
    public static final String KEY_REPORT_CHAT_NIKE_NAME = "KEY_REPORT_CHAT_NIKE_NAME";
    public static final String KEY_REPORT_CHAT_IMG_PATH = "KEY_REPORT_CHAT_IMG_PATH";
    public static final String KEY_REPORT_CHAT_CONTENT = "KEY_REPORT_CHAT_CONTENT";
    public static final String KEY_REPORT_CHAT_CREATE_TIME = "KEY_REPORT_CHAT_CREATE_TIME";
    public static final String KEY_REPORT_CHAT_TYPE = "KEY_REPORT_CHAT_TYPE";
    public static final String KEY_REPORT_NOW = "KEY_REPORT_NOW";


    private BroadcastReceiver mReportReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final Bundle bundle = intent.getExtras();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (null != bundle) {
                        String talker = bundle.getString(KEY_REPORT_CHAT_TALKER);
                        String nikeName = bundle.getString(KEY_REPORT_CHAT_NIKE_NAME);
                        String path = bundle.getString(KEY_REPORT_CHAT_IMG_PATH);
                        String content = bundle.getString(KEY_REPORT_CHAT_CONTENT);
                        long createTime = bundle.getLong(KEY_REPORT_CHAT_CREATE_TIME);
                        int type = bundle.getInt(KEY_REPORT_CHAT_TYPE);
                        boolean reportNow = bundle.getBoolean(KEY_REPORT_NOW);
                        LogManager.getInstance().logInfo("上传消息 talker = " + talker + " nikeName = " + nikeName + " path = " + path + " content = " + content + " createTime = " + createTime + " type = " + type + " reportNow = " + reportNow);
                        ReportMessage.getInstance(TaskLogicService.this).report(mAccount, talker, nikeName, path, content, createTime, type, reportNow);
                    }
                }
            }).start();
        }
    };

    private void setAirPlan(boolean state) {
        if (MockServices.checkClient()) {
            try {
                MockServices.getClient().setMobileDataEnable(state);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        try {
            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            intent.putExtra("state", state);
            sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
            LogManager.getInstance().logError("setAirPlan Exception");
            showToast("请检查飞行模式插件是否正常");
        }
    }

    private void showToast(final String msg) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(TaskLogicService.this, msg, Toast.LENGTH_LONG).show();
            }
        }, 10);
    }

    private boolean preProcessTask(TaskBean taskBean) {
        if (null == taskBean) {
            return false;
        }

        if (taskBean.getTaskId() == WxTaskProcess.TASK_ID_SEND_FRIEND_CIRCLE) {
            String extra = taskBean.getExtra();
            deleteAllRandomPicCache();
            try {
                JSONObject jsonObject = new JSONObject(extra);
                JSONArray jsonArray = jsonObject.getJSONArray("images");
                JSONArray sendPicArray = new JSONArray();
                for (int i = 0, len = jsonArray.length(); i < len; i++) {
                    String img = jsonArray.getString(i);

                    String fileName = img.substring(img.lastIndexOf("/") + 1);
                    boolean exitMsPic = checkPic();
                    if (!exitMsPic) {
                        return false;
                    }
                    String savePath = new File(AccountManager.PICTURE_PATH, fileName).getAbsolutePath();
                    String url = UrlConfig.URL_BASE + img;
                    LogManager.getInstance().logInfo("img " + img + " url = " + url + " savePath = " + savePath);
                    File picFile = new File(savePath);
                    if (picFile.exists()) {
                        LogManager.getInstance().logInfo("文件已经存在");
                        String randomPicPath = randomBitmap(savePath);
                        if (TextUtils.isEmpty(randomPicPath)) {
                            LogManager.getInstance().logError("处理图片失败");
                            return false;
                        } else {
                            sendPicArray.put(randomPicPath);
                        }
                    } else {
                        boolean downSuccess = DownloadFile.downLoad(url, savePath);
                        if (!downSuccess) {
                            boolean deleteFailedFile = picFile.delete();
                            if (!deleteFailedFile) {
                                LogManager.getInstance().logError("删除下载失败的文件错误");
                            }
                            return false;
                        } else {
                            String randomPicPath = randomBitmap(savePath);
                            if (TextUtils.isEmpty(randomPicPath)) {
                                LogManager.getInstance().logError("处理图片失败");
                                return false;
                            } else {
                                sendPicArray.put(randomPicPath);
                            }
                        }
                    }
                }
                jsonObject.put(WxUiViewConfig.KEY_FRIEND_CIRCLE_PATHS, sendPicArray.toString());
                taskBean.setExtra(jsonObject.toString());
            } catch (JSONException e) {
                e.printStackTrace();
                LogManager.getInstance().logError("解析Json错误");
                return false;
            }
        } else if (taskBean.getTaskId() == WxTaskProcess.TASK_ID_ADD_CONTACTS_FRIEND) {
            ContactsManager.getInstance().processAccountContacts(taskBean.getAccount(), taskBean.getExtra());
        } else if (taskBean.getTaskId() == WxTaskProcess.TASK_CHANGE_FRIEND_BACK || taskBean.getTaskId() == WxTaskProcess.TASK_CHANGE_ICON) {
            String extra = taskBean.getExtra();
            deleteAllRandomPicCache();
            try {
                JSONObject jsonObject = new JSONObject(extra);
                if (jsonObject.has(WxUiViewConfig.CHANGE_ICON_PATH)) {
                    String urlPath = jsonObject.getString(WxUiViewConfig.CHANGE_ICON_PATH);
                    String fileName = urlPath.substring(urlPath.lastIndexOf("/") + 1);
                    String savePath = new File(AccountManager.PICTURE_PATH, fileName).getAbsolutePath();

                    boolean exitMsPic = checkPic();
                    if (!exitMsPic) {
                        return false;
                    }

                    String url = UrlConfig.URL_BASE + urlPath;
                    LogManager.getInstance().logInfo(" url = " + url + " savePath = " + savePath);
                    File picFile = new File(savePath);
                    if (picFile.exists()) {
                        LogManager.getInstance().logInfo("文件已经存在");
                        String randomPicPath = randomBitmap(savePath);
                        if (TextUtils.isEmpty(randomPicPath)) {
                            LogManager.getInstance().logError("处理图片失败");
                            return false;
                        } else {
                            jsonObject.put(WxUiViewConfig.CHANGE_ICON_PATH, randomPicPath);
                        }
                    } else {
                        boolean downSuccess = DownloadFile.downLoad(url, savePath);
                        if (!downSuccess) {
                            LogManager.getInstance().logError("下载文件错误");
                            boolean deleteFailedFile = picFile.delete();
                            if (!deleteFailedFile) {
                                LogManager.getInstance().logError("删除下载失败的文件错误");
                            }
                            return false;
                        } else {
                            String randomPicPath = randomBitmap(savePath);
                            if (TextUtils.isEmpty(randomPicPath)) {
                                LogManager.getInstance().logError("处理图片失败");
                                return false;
                            } else {
                                jsonObject.put(WxUiViewConfig.CHANGE_ICON_PATH, randomPicPath);
                            }
                        }
                    }
                }

                taskBean.setExtra(jsonObject.toString());
                LogManager.getInstance().logError("new extra = " + taskBean.getExtra());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if (taskBean.getTaskId() == WxTaskProcess.TASK_ID_ADD_NEARBY_FRIEND) {
            PackageTool.stopApp(AccountManager.WX_PACKAGE_NAME);
        }
        return true;
    }

    public static boolean checkPic() {
        File picRoot = new File(AccountManager.PICTURE_PATH);
        if (!picRoot.exists()) {
            boolean success = picRoot.mkdir();
            LogManager.getInstance().logInfo("创建文件夹 " + AccountManager.PICTURE_PATH + success);
            if (!success) {
                LogManager.getInstance().logError("创建文件失败");
                return false;
            }
        }
        return true;
    }

    private void deleteAllRandomPicCache() {
        File randomRootPath = new File(AccountManager.PICTURE_RANDOM_PATH);
        if (randomRootPath.exists()) {
            File[] files = randomRootPath.listFiles();
            for (File f : files) {
                boolean delete = f.delete();
                LogManager.getInstance().logInfo("删除文件 " + f.getAbsolutePath() + " " + delete);
            }
        } else {
            randomRootPath.mkdir();
        }
    }

    public static String randomBitmap(String picPath) {
        if (TextUtils.isEmpty(picPath)) {
            return "";
        }
        Bitmap bp = BitmapFactory.decodeFile(picPath).copy(Bitmap.Config.ARGB_8888, true);
        int x = mRandom.nextInt(bp.getWidth());
        int y = mRandom.nextInt(bp.getHeight());
        bp.setPixel(x, y, 0x00ffffff);
//        bp.setPixel(x, y, (0xff000000 | mRandom.nextInt(0x00ffffff)));
        String fileName = UUID.randomUUID().toString() + ".jpg";
        File randomRootPath = new File(AccountManager.PICTURE_RANDOM_PATH);
        if (!randomRootPath.exists()) {
            boolean randomPathCreate = randomRootPath.mkdir();
            if (!randomPathCreate) {
                LogManager.getInstance().logError("创建文件夹失败 " + AccountManager.PICTURE_RANDOM_PATH);
                return "";
            }
        }
        File newPicFile = new File(randomRootPath, fileName);
        if (newPicFile.exists()) {
            boolean deleteRandomFile = newPicFile.delete();
            if (!deleteRandomFile) {
                LogManager.getInstance().logError("删除文件失败 " + newPicFile.getAbsolutePath());
                return "";
            }
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(newPicFile);
            bp.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            LogManager.getInstance().logError("randomBitmap FileNotFoundException " + newPicFile.getAbsolutePath() + e.toString());
            return "";
        } catch (IOException e) {
            e.printStackTrace();
            LogManager.getInstance().logError("randomBitmap IOException " + newPicFile.getAbsolutePath() + e.toString());
            return "";
        } finally {
            try {
                if (null != out)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
                LogManager.getInstance().logError("randomBitmap out.close() IOException " + newPicFile.getAbsolutePath() + e.toString());
            }
        }
        return newPicFile.getAbsolutePath();

    }

    public static void sendKeyEvent(Context context, int keyCode) {
        if (null == context) {
            return;
        }
        Intent intent = new Intent(TaskLogicService.ACTION_KEY_RECEIVER);
        Bundle bundle = new Bundle();
        bundle.putInt(TaskLogicService.KEY_INPUT_KEY, keyCode);
        intent.putExtras(bundle);
        context.sendBroadcast(intent);
    }

    private Runnable mCheckNewMessage = new Runnable() {
        @Override
        public void run() {
            mHandler.removeCallbacks(mCheckNewMessage);
            boolean business = ActSetting.isBusinessVersion(TaskLogicService.this);
            LogManager.getInstance().logInfo("mCheckNewMessage");
            if (business)
                requestNewMessage();
            mHandler.postDelayed(mCheckNewMessage, REQUEST_MESSAGE_STEP);
        }
    };

    private void requestNewMessage() {
        if (TextUtils.isEmpty(mAccount)) {
            if (!syncDeviceInfo()) {
                LogManager.getInstance().logInfo("获取账号失败");
                return;
            }
        }

        String url = String.format(UrlConfig.URL_GET_NEW_MESSAGE, mAccount);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                LogManager.getInstance().logInfo("response = " + response);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (null != jsonObject && jsonObject.has("code")) {
                    try {
                        int code = jsonObject.getInt("code");
                        if (0 == code) {
                            if (jsonObject.has("chats")) {
                                final JSONObject finalJsonObject = jsonObject;
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            int insertNum = ChatNewChatDB.getInstance().insertMessage(finalJsonObject.get("chats").toString());
                                            LogManager.getInstance().logInfo("insertNum = " + insertNum);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            } else {
                                LogManager.getInstance().logInfo("chats not find");
                            }
                        } else {
                            if (jsonObject.has("messages")) {
                                LogManager.getInstance().logInfo(" " + jsonObject.getString("messages"));
                            } else {
                                LogManager.getInstance().logInfo("not find message ");
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        LogManager.getInstance().logError("onResponse JSONException " + e.toString());
                    }
                } else {
                    LogManager.getInstance().logInfo("no code ");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (null != error && error.getMessage() != null) {
                    LogManager.getInstance().logError("requestNewMessage error msg =  " + error.getMessage());
                } else {
                    LogManager.getInstance().logError("requestNewMessage error msg = null ");
                }
            }
        });

        queue.add(stringRequest);
    }

    public static final String ACTION_KEY_REPORT_ACCOUNT_ICON = "ACTION_KEY_REPORT_ACCOUNT_ICON";
    public static final String ACTION_KEY_REPORT_FRIEND_ICON = "ACTION_KEY_REPORT_FRIEND_ICON";
    public static final String ACTION_KEY_REPORT_FRIEND_SEX = "ACTION_KEY_REPORT_FRIEND_SEX";
    public static final String KEY_SEX_TALKER = "KEY_SEX_TALKER";
    public static final String KEY_SEX_SEX = "KEY_SEX_SEX";

    private BroadcastReceiver mReportIconPath = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            LogManager.getInstance().logInfo("ACTION_KEY_REPORT_FRIEND_ICON");
            if (ACTION_KEY_REPORT_ACCOUNT_ICON.equals(action)) {
                LogManager.getInstance().logError("开始上报个人头像");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ReportIcon.getInstance().reportAccountIcon(mAccount);
                    }
                }).start();
            } else if (ACTION_KEY_REPORT_FRIEND_ICON.equals(action)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ReportIcon.getInstance().reportFriendIcon(mAccount);
                    }
                }).start();
            } else if (ACTION_KEY_REPORT_FRIEND_SEX.equals(action)) {
                Bundle extras = intent.getExtras();
                if (null != extras) {
                    String talker = extras.getString(KEY_SEX_TALKER);
                    String sex = extras.getString(KEY_SEX_SEX);
                    long changeSex = ChatNewChatDB.getInstance().changeFriendSex(talker, sex);
                    LogManager.getInstance().logInfo("改变性别 talker = " + talker + " sex = " + sex + " changeSex = " + changeSex);
                }
            }
        }
    };

    public static final String ACTION_REBOOT = "ACTION_REBOOT";
    private BroadcastReceiver mRebootReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            LogManager.getInstance().logInfo("ACTION_REBOOT");
            ShellOperationTool.reBoot();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getTask(0, "ACTION_REBOOT 当前服务没有运行");
                }
            }, 3000);


            context.sendBroadcast(new Intent("com.tevintao.receiver.autoreboot"));
        }
    };

    public static final String ACTION_REPORT_SYSTEM_ERROR = "ACTION_REPORT_SYSTEM_ERROR";
    public static final String KEY_ERROR_MESSAGE = "KEY_ERROR_MESSAGE";
    private BroadcastReceiver mSystemErrorReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle extras = intent.getExtras();
            if (null != extras) {
                String msg = extras.getString(KEY_ERROR_MESSAGE);
                if (!TextUtils.isEmpty(msg)) {
                    saveSendMsg(msg);
                }
            }


        }
    };


    private void saveSendMsg(String content) {
        try {
            //打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(AccountManager.SYSTEM_ERROR_MESSAGE_FILE, true);
            writer.write(content + "\r\n");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
